﻿using System;
using System.IO;

namespace FileAndDirectoryDateReset
{
    class Program
    {
        private const string messageOk = "Date successfully updated";
        private const string messageError = "Error while updating date: ";

        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("Please drag and drop files on the program executable to have their dates reset to the current time.");
                Console.WriteLine("Press any key to exit...");
                Console.ReadKey();
                return;
            }

            foreach (string arg in args)
            {
                ResetDate(arg);
            }
            Console.ReadKey();
        }


        private static void ResetDate(string arg)
        {
            if (File.Exists(arg))
            {
                ResetFileDate(arg);
            }

            else if (Directory.Exists(arg))
            {
                var files = Directory.GetFiles(arg);
                foreach (var file in files)
                {
                    ResetFileDate(file);
                }

                var directories = Directory.GetDirectories(arg);
                foreach (var directory in directories)
                {
                    ResetDate(directory);
                }

                ResetDirectoryDate(arg);
            }
        }


        static private void ResetDirectoryDate(string arg)
        {
            Console.WriteLine("Updating folder \"{0}\"", arg);
            try
            {
                Directory.SetCreationTime(arg, DateTime.Now);
                Directory.SetLastAccessTime(arg, DateTime.Now);
                Directory.SetLastWriteTime(arg, DateTime.Now);

                WriteMessage(success: true);
            }
            catch (Exception e)
            {
                WriteMessage(success: false, e: e);
            }
        }


        static private void ResetFileDate(string arg)
        {
            Console.WriteLine("Updating file \"{0}\"", arg);
            try
            {
                File.SetCreationTime(arg, DateTime.Now);
                File.SetLastAccessTime(arg, DateTime.Now);
                File.SetLastWriteTime(arg, DateTime.Now);

                WriteMessage(success: true);
            }
            catch (Exception e)
            {
                WriteMessage(success: false, e: e);
            }
        }



        static private void WriteMessage(bool success, Exception e = null)
        {
            var message = success ? messageOk : messageError + e;
            message += Environment.NewLine;

            Console.ForegroundColor = success ? ConsoleColor.DarkGreen : ConsoleColor.DarkRed;
            Console.WriteLine(message);
            Console.ForegroundColor = ConsoleColor.Gray;
        }
    }
}
